package com.future.config;

import com.future.WebSocket.ChatWebSocketHandler;
import com.future.WebSocket.WebSocketAuthInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
    private final ChatWebSocketHandler chatWebSocketHandler;
    private final WebSocketAuthInterceptor webSocketAuthInterceptor;

    // 通过构造函数注入（确保 Handler 和 Interceptor 已实例化）
    public WebSocketConfig(ChatWebSocketHandler chatWebSocketHandler, WebSocketAuthInterceptor webSocketAuthInterceptor) {
        this.chatWebSocketHandler = chatWebSocketHandler;
        this.webSocketAuthInterceptor = webSocketAuthInterceptor;
    }

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(chatWebSocketHandler, "/ws/chat") // 关键：路径必须匹配客户端连接的地址
                .addInterceptors(webSocketAuthInterceptor) // 添加拦截器（用于解析用户ID）
                .setAllowedOrigins("*"); // 允许跨域（开发阶段）
    }
}
